package 面试题;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: MENG
 * Date: 2022-07-12
 * Time: 19:21
 */
//实现一个最小栈
public class MinStack {
    private Stack<Integer> s ;//普通栈
    private Stack<Integer> minStack ;// 维护当前栈的最小值

    public MinStack() {
        this.s = new Stack<>();
        this.minStack = new Stack<>();
    }

    /*
     * 入栈
     * */
    public void push(int val){
        s.push(val);
        if(minStack.empty()){
            minStack.push(val);
        }else{
            //val是 普通类型，不能用==和引用类型比较
//        if(val <= minStack.peek())
            int peekV = minStack.peek();
            if(val <= peekV){
                minStack.push(val);
            }
        }
    }


    /**
     * 出栈
     */
    public void pop(){
        if(!s.empty()){
            int popV = s.pop();
            int peekVMin = minStack.pop();
            if(popV == peekVMin){
                minStack.pop();
            }
        }

    }

    //获取栈顶元素,但是不删除
    public int top() {
        if(!s.empty()) {
            return s.peek();
        }
        return -1;
    }
    //获取最小栈的栈顶元素
    public int getMin() {
        if(!minStack.empty()) {
            return minStack.peek();
        }
        return -1;
    }

}